package com.example.park2212.sign

import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.baidu.mapapi.map.BaiduMap
import com.baidu.mapapi.map.MapStatusUpdateFactory
import com.baidu.mapapi.map.MapView
import com.baidu.mapapi.map.MyLocationData
import com.baidu.mapapi.model.LatLng
import com.blankj.utilcode.util.SPUtils
import com.example.lib_base.entity.SignBeanItem
import com.example.lib_base.mvvm.BaseActivity
import com.example.lib_base.net.Const
import com.example.park2212.databinding.ActivitySignBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.Timer
import kotlin.concurrent.timerTask


@AndroidEntryPoint
@Route(path = "/app/sign/SignActivity")
class SignActivity : BaseActivity<ActivitySignBinding,SignViewModel>() {
    var mapView:MapView?=null
    var baiduMap:BaiduMap?=null
    var mLocationClient : LocationClient? = null
    var timer:Timer?=null

    override fun initView() {
        initMap()
        val spUtils = SPUtils.getInstance()


        val signTime = spUtils.getString("sign", "")//取出签到的日期时间
        val today = viewModel.getDate(System.currentTimeMillis())
        if (signTime.isNotEmpty()){//说明打过签到卡
            if (signTime.split(" ")[0] == today){//说明今天打过签到
                val time = signTime.split(" ")[1]
                binding.signStartTime.setText(time)
                if (time>"09:00:00"){
                    binding.signStartTime.append("(迟到)")
                }
                binding.tvSignText.setText("签退")
            }

            val soutTime = spUtils.getString("sout", "")//取出签退的日期时间
            if (soutTime.isNotEmpty()){//
                if (soutTime.split(" ")[0] == today){
                    val time = soutTime.split(" ")[1]
                    binding.signEndTime.setText(time)
                    if (time<"18:00:00"){
                        binding.signEndTime.append("(早退)")
                    }

                    binding.btnSign.isEnabled = false
                }
        }
    }


        lifecycleScope.launch {
            timer = Timer()
            timer?.schedule(timerTask {
                lifecycleScope.launch(Dispatchers.Main) {
                    binding.tvTime.setText(viewModel.getTime(System.currentTimeMillis()))
                }
            },0,1000)
        }

        binding.btnSign.apply {
            setOnClickListener {
                var item:SignBeanItem?=null
                var status = "正常"
                val dateTime = viewModel.getDateTime(System.currentTimeMillis())
                val time = dateTime.split(" ")[1]
                if (binding.tvSignText.text.toString() == "签到"){
                    binding.signStartTime.setText(time)
                    if (time>"09:00:00"){
                        status = "迟到"
                        binding.signStartTime.append("(${status})")
                    }
                    item = SignBeanItem(
                        "", "",
                        null,"天津", dateTime,
                        status, SPUtils.getInstance().getInt(Const.UID),
                        null)

                    binding.tvSignText.setText("签退")
                    spUtils.put("sign",dateTime)
                }else{
                    binding.signEndTime.setText(time)
                    if (time<"18:00:00"){
                        status = "早退"
                        binding.signEndTime.append("(${status})")
                    }
                    item = SignBeanItem(
                        dateTime, "",
                        null,"天津", "",
                        status, SPUtils.getInstance().getInt(Const.UID),
                        null)
                    isEnabled = false
                    spUtils.put("sout",dateTime)
                }
                viewModel.sign(item)
            }
        }
    }

   private fun initMap(){

        mapView = binding.mapView
        baiduMap = mapView!!.map
        baiduMap!!.isMyLocationEnabled = true

        LocationClient.setAgreePrivacy(true)
        //定位初始化
        //定位初始化
         mLocationClient = LocationClient(this)

//通过LocationClientOption设置LocationClient相关参数

//通过LocationClientOption设置LocationClient相关参数
        val option = LocationClientOption()
        option.isOpenGps = true // 打开gps

        option.setCoorType("bd09ll") // 设置坐标类型

        option.setScanSpan(1000)

//设置locationClientOption

//设置locationClientOption
        mLocationClient?.setLocOption(option)

//注册LocationListener监听器

//注册LocationListener监听器
        val myLocationListener = MyLocationListener()
        mLocationClient?.registerLocationListener(myLocationListener)
//开启地图定位图层
//开启地图定位图层
        mLocationClient?.start()
    }

    inner class MyLocationListener : BDAbstractLocationListener() {
        override fun onReceiveLocation(location: BDLocation) {
            //mapView 销毁后不在处理新接收的位置
            if (location == null || mapView == null) {
                return
            }
            val locData = MyLocationData.Builder()
                .accuracy(location.radius) // 此处设置开发者获取到的方向信息，顺时针0-360
                .direction(location.direction).latitude(location.latitude)
                .longitude(location.longitude).build()


            //定位置点额外加的
            val latLng = LatLng(location.latitude, location.longitude)
            val update = MapStatusUpdateFactory.newLatLngZoom(latLng, 5f)
            //baiduMap!!.animateMapStatus(update)
            baiduMap!!.setMyLocationData(locData)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mLocationClient?.stop()
        baiduMap?.setMyLocationEnabled(false)
        mapView?.onDestroy()
        mapView = null
        if (timer!= null){
            timer?.cancel()
            timer == null
        }
    }

    override fun initData() {

    }

}